

import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, TextInput, Modal, Alert, Image, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface AttachmentItem {
  id: string;
  name: string;
  size: string;
  uploader: string;
  date: string;
  type: 'pdf' | 'docx';
}

interface ProgressNode {
  id: string;
  title: string;
  assignee: string;
  status: 'completed' | 'active' | 'pending';
  time?: string;
}

interface CommentItem {
  id: string;
  author: string;
  avatar: string;
  time: string;
  action: string;
  comment: string;
  status: 'approved' | 'rejected' | 'submitted';
}

const ApprovalDetailScreen: React.FC = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  
  const [approvalComment, setApprovalComment] = useState('');
  const [isMoreActionsMenuVisible, setIsMoreActionsMenuVisible] = useState(false);

  // 模拟数据
  const approvalData = {
    title: '员工请假申请',
    initiator: '李小红',
    initiateTime: '2024-01-15 14:30',
    status: 'pending',
    type: '人事审批',
    formData: {
      leaveType: '年假',
      leaveDays: '5天',
      startTime: '2024-01-20',
      endTime: '2024-01-24',
      reason: '春节回家探亲，与家人团聚',
      departmentHead: '张明',
    },
  };

  const attachments: AttachmentItem[] = [
    {
      id: '1',
      name: '请假申请单.pdf',
      size: '2.3 MB',
      uploader: '李小红',
      date: '2024-01-15',
      type: 'pdf',
    },
    {
      id: '2',
      name: '工作交接清单.docx',
      size: '1.8 MB',
      uploader: '李小红',
      date: '2024-01-15',
      type: 'docx',
    },
  ];

  const progressNodes: ProgressNode[] = [
    {
      id: '1',
      title: '提交申请',
      assignee: '李小红',
      status: 'completed',
      time: '2024-01-15 14:30',
    },
    {
      id: '2',
      title: '部门经理审批',
      assignee: '张明',
      status: 'active',
    },
    {
      id: '3',
      title: '人事部门审批',
      assignee: '',
      status: 'pending',
    },
    {
      id: '4',
      title: '总经理审批',
      assignee: '',
      status: 'pending',
    },
  ];

  const comments: CommentItem[] = [
    {
      id: '1',
      author: '李小红',
      avatar: 'https://s.coze.cn/image/_qR-78fRe7A/',
      time: '2024-01-15 14:30',
      action: '提交申请',
      comment: '提交了请假申请，等待审批',
      status: 'submitted',
    },
  ];

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleMoreActionsPress = () => {
    setIsMoreActionsMenuVisible(true);
  };

  const handleCloseMoreActionsMenu = () => {
    setIsMoreActionsMenuVisible(false);
  };

  const handleViewFlowPress = () => {
    const processInstanceId = params.processInstanceId || 'default';
    router.push(`/p-approval_flow?processInstanceId=${processInstanceId}`);
  };

  const handleUrgePress = () => {
    Alert.alert('催办成功', '催办通知已发送');
    setIsMoreActionsMenuVisible(false);
  };

  const handleSharePress = () => {
    Alert.alert('分享功能', '分享功能开发中');
    setIsMoreActionsMenuVisible(false);
  };

  const handleAttachmentPress = (attachment: AttachmentItem) => {
    Alert.alert('附件预览', `查看 ${attachment.name}`);
  };

  const handleAddAttachmentPress = () => {
    Alert.alert('添加附件', '文件选择功能开发中');
  };

  const handleApprovalAction = (action: 'approve' | 'reject' | 'transfer' | 'back') => {
    const actionText = action === 'approve' ? '通过' : 
                      action === 'reject' ? '驳回' : 
                      action === 'transfer' ? '转办' : '退回上一步';
    
    Alert.alert(
      '确认操作',
      `确定要${actionText}此审批吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            const processInstanceId = params.processInstanceId || 'default';
            router.push(`/p-approval_process?processInstanceId=${processInstanceId}&action=${action}&comment=${encodeURIComponent(approvalComment)}`);
          },
        },
      ]
    );
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'completed':
        return '已完成';
      case 'active':
        return '处理中';
      default:
        return '待处理';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return '#10B981';
      case 'active':
        return '#969FFF';
      default:
        return '#6B7280';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return 'check';
      case 'active':
        return 'user';
      default:
        return 'clock';
    }
  };

  const getAttachmentIcon = (type: string) => {
    return type === 'pdf' ? 'file-pdf' : 'file-word';
  };

  const getAttachmentGradient = (type: string) => {
    return type === 'pdf' ? ['#3B82F6', '#2563EB'] : ['#10B981', '#059669'];
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity style={styles.headerButton} onPress={handleBackPress}>
          <FontAwesome6 name="arrow-left" size={18} color="#1F2937" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>审批详情</Text>
        <TouchableOpacity style={styles.headerButton} onPress={handleMoreActionsPress}>
          <FontAwesome6 name="ellipsis-vertical" size={18} color="#6B7280" />
        </TouchableOpacity>
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 审批基本信息 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.approvalInfoHeader}>
              <View style={styles.approvalInfoLeft}>
                <Text style={styles.approvalTitle}>{approvalData.title}</Text>
                <View style={styles.approvalMeta}>
                  <View style={styles.metaItem}>
                    <FontAwesome6 name="user" size={12} color="#6B7280" />
                    <Text style={styles.metaText}>{approvalData.initiator}</Text>
                  </View>
                  <View style={styles.metaItem}>
                    <FontAwesome6 name="clock" size={12} color="#6B7280" />
                    <Text style={styles.metaText}>{approvalData.initiateTime}</Text>
                  </View>
                </View>
              </View>
              <View style={styles.statusBadge}>
                <Text style={styles.statusText}>待审批</Text>
              </View>
            </View>
            
            <View style={styles.approvalTypeRow}>
              <View style={styles.approvalTypeLeft}>
                <FontAwesome6 name="tag" size={14} color="#969FFF" />
                <Text style={styles.approvalTypeLabel}>审批类型</Text>
              </View>
              <Text style={styles.approvalTypeValue}>{approvalData.type}</Text>
            </View>
          </View>
        </View>

        {/* 审批表单内容 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.cardHeader}>
              <FontAwesome6 name="file-lines" size={16} color="#969FFF" />
              <Text style={styles.cardTitle}>表单内容</Text>
            </View>
            <View style={styles.formFields}>
              <View style={styles.formField}>
                <Text style={styles.formLabel}>请假类型</Text>
                <Text style={styles.formValue}>{approvalData.formData.leaveType}</Text>
              </View>
              <View style={styles.formField}>
                <Text style={styles.formLabel}>请假天数</Text>
                <Text style={styles.formValue}>{approvalData.formData.leaveDays}</Text>
              </View>
              <View style={styles.formField}>
                <Text style={styles.formLabel}>请假时间</Text>
                <View style={styles.dateRange}>
                  <Text style={styles.formValue}>{approvalData.formData.startTime}</Text>
                  <Text style={styles.dateConnector}>至</Text>
                  <Text style={styles.formValue}>{approvalData.formData.endTime}</Text>
                </View>
              </View>
              <View style={styles.formField}>
                <Text style={styles.formLabel}>请假事由</Text>
                <Text style={styles.formValue}>{approvalData.formData.reason}</Text>
              </View>
              <View style={[styles.formField, styles.lastFormField]}>
                <Text style={styles.formLabel}>部门负责人</Text>
                <Text style={styles.formValue}>{approvalData.formData.departmentHead}</Text>
              </View>
            </View>
          </View>
        </View>

        {/* 附件查看 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.cardHeader}>
              <FontAwesome6 name="paperclip" size={16} color="#969FFF" />
              <Text style={styles.cardTitle}>附件</Text>
              <Text style={styles.attachmentCount}>({attachments.length}个)</Text>
            </View>
            <View style={styles.attachmentList}>
              {attachments.map((attachment, index) => (
                <TouchableOpacity
                  key={attachment.id}
                  style={[styles.attachmentItem, index === attachments.length - 1 && styles.lastAttachmentItem]}
                  onPress={() => handleAttachmentPress(attachment)}
                >
                  <View style={styles.attachmentLeft}>
                    <LinearGradient
                      colors={getAttachmentGradient(attachment.type)}
                      style={styles.attachmentIcon}
                    >
                      <FontAwesome6 name={getAttachmentIcon(attachment.type)} size={16} color="#FFFFFF" />
                    </LinearGradient>
                    <View style={styles.attachmentInfo}>
                      <Text style={styles.attachmentName}>{attachment.name}</Text>
                      <Text style={styles.attachmentMeta}>{attachment.size} · {attachment.uploader} · {attachment.date}</Text>
                    </View>
                  </View>
                  <FontAwesome6 name="download" size={16} color="#6B7280" />
                </TouchableOpacity>
              ))}
            </View>
          </View>
        </View>

        {/* 审批流程进度 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.cardHeaderWithAction}>
              <View style={styles.cardHeader}>
                <FontAwesome6 name="route" size={16} color="#969FFF" />
                <Text style={styles.cardTitle}>审批进度</Text>
              </View>
              <TouchableOpacity style={styles.viewFlowButton} onPress={handleViewFlowPress}>
                <Text style={styles.viewFlowText}>查看流程图</Text>
                <FontAwesome6 name="chevron-right" size={12} color="#969FFF" />
              </TouchableOpacity>
            </View>
            <View style={styles.progressContainer}>
              {progressNodes.map((node, index) => (
                <View key={node.id} style={[styles.progressNode, index === progressNodes.length - 1 && styles.lastProgressNode]}>
                  <View style={[styles.progressNodeIcon, { backgroundColor: getStatusColor(node.status) }]}>
                    <FontAwesome6 name={getStatusIcon(node.status)} size={12} color="#FFFFFF" />
                  </View>
                  <View style={styles.progressNodeContent}>
                    <Text style={[styles.progressNodeTitle, node.status !== 'completed' && styles.progressNodeTitlePending]}>
                      {node.title}
                    </Text>
                    <Text style={styles.progressNodeMeta}>
                      {node.assignee} {node.time ? `· ${node.time}` : node.status === 'active' ? '· 当前处理人' : ''}
                    </Text>
                    <Text style={[styles.progressNodeStatus, { color: getStatusColor(node.status) }]}>
                      {getStatusText(node.status)}
                    </Text>
                  </View>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* 历史审批记录 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.cardHeader}>
              <FontAwesome6 name="clock-rotate-left" size={16} color="#969FFF" />
              <Text style={styles.cardTitle}>审批记录</Text>
            </View>
            <View style={styles.commentList}>
              {comments.map((comment, index) => (
                <View key={comment.id} style={[styles.commentItem, index === comments.length - 1 && styles.lastCommentItem]}>
                  <View style={styles.commentContent}>
                    <Image source={{ uri: comment.avatar }} style={styles.commentAvatar} />
                    <View style={styles.commentText}>
                      <View style={styles.commentHeader}>
                        <Text style={styles.commentAuthor}>{comment.author}</Text>
                        <Text style={styles.commentTime}>{comment.time}</Text>
                        <View style={styles.commentActionBadge}>
                          <Text style={styles.commentActionText}>{comment.action}</Text>
                        </View>
                      </View>
                      <Text style={styles.commentTextContent}>{comment.comment}</Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* 审批操作区 */}
        <View style={styles.section}>
          <View style={styles.card}>
            <View style={styles.cardHeader}>
              <FontAwesome6 name="pen-to-square" size={16} color="#969FFF" />
              <Text style={styles.cardTitle}>审批操作</Text>
            </View>
            
            {/* 审批意见 */}
            <View style={styles.commentSection}>
              <Text style={styles.commentLabel}>审批意见</Text>
              <TextInput
                style={styles.commentInput}
                value={approvalComment}
                onChangeText={setApprovalComment}
                placeholder="请输入您的审批意见..."
                multiline
                numberOfLines={3}
                textAlignVertical="top"
              />
            </View>
            
            {/* 添加附件/备注 */}
            <TouchableOpacity style={styles.addAttachmentButton} onPress={handleAddAttachmentPress}>
              <FontAwesome6 name="plus" size={16} color="#6B7280" />
              <Text style={styles.addAttachmentText}>添加附件或备注</Text>
            </TouchableOpacity>
            
            {/* 操作按钮 */}
            <View style={styles.actionButtons}>
              <View style={styles.actionButtonRow}>
                <TouchableOpacity
                  style={styles.rejectButton}
                  onPress={() => handleApprovalAction('reject')}
                >
                  <FontAwesome6 name="xmark" size={14} color="#EF4444" />
                  <Text style={styles.rejectButtonText}>驳回</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.approveButton}
                  onPress={() => handleApprovalAction('approve')}
                >
                  <LinearGradient
                    colors={['#969FFF', '#5147FF']}
                    style={styles.approveButtonGradient}
                  >
                    <FontAwesome6 name="check" size={14} color="#FFFFFF" />
                    <Text style={styles.approveButtonText}>通过</Text>
                  </LinearGradient>
                </TouchableOpacity>
              </View>
              <View style={styles.actionButtonRow}>
                <TouchableOpacity
                  style={styles.transferButton}
                  onPress={() => handleApprovalAction('transfer')}
                >
                  <FontAwesome6 name="share" size={14} color="#3B82F6" />
                  <Text style={styles.transferButtonText}>转办</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.backButton}
                  onPress={() => handleApprovalAction('back')}
                >
                  <FontAwesome6 name="arrow-left" size={14} color="#6B7280" />
                  <Text style={styles.backButtonText}>退回上一步</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </View>

        {/* 催办按钮 */}
        <View style={styles.section}>
          <TouchableOpacity style={styles.urgeButton} onPress={handleUrgePress}>
            <FontAwesome6 name="bell" size={16} color="#F97316" />
            <Text style={styles.urgeButtonText}>催办此审批</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>

      {/* 更多操作菜单 */}
      <Modal
        visible={isMoreActionsMenuVisible}
        transparent
        animationType="fade"
        onRequestClose={handleCloseMoreActionsMenu}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={handleCloseMoreActionsMenu}
        >
          <View style={styles.modalContent}>
            <View style={styles.modalHandle} />
            <TouchableOpacity style={styles.modalItem} onPress={handleUrgePress}>
              <FontAwesome6 name="bell" size={18} color="#F97316" />
              <Text style={styles.modalItemText}>催办审批</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.modalItem} onPress={handleSharePress}>
              <FontAwesome6 name="share-nodes" size={18} color="#3B82F6" />
              <Text style={styles.modalItemText}>分享审批</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.modalItem} onPress={handleCloseMoreActionsMenu}>
              <FontAwesome6 name="xmark" size={18} color="#6B7280" />
              <Text style={styles.modalItemText}>取消</Text>
            </TouchableOpacity>
          </View>
        </TouchableOpacity>
      </Modal>
    </SafeAreaView>
  );
};

export default ApprovalDetailScreen;

